/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Presentacion;

import ModeloLogicoSistema.AdministradorServicio;
import ModeloLogicoSistema.Servicio;
import java.awt.HeadlessException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author debo
 */
public class BuscarServicios extends javax.swing.JDialog {

    ArrayList<Servicio> servicios=null;
    AdministradorServicio adm;
    Servicio servicio;
    
    public BuscarServicios(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
       this.setLocationRelativeTo(null);
        try {
            this.adm=new AdministradorServicio();
            this.cargarTablaServicio();
        } catch (SQLException ex) {
            Logger.getLogger(BuscarServicios.class.getName()).log(Level.SEVERE, null, ex);
        }
        DefaultTableModel modelo=(DefaultTableModel)this.jTable1.getModel();
        TableRowSorter<TableModel> elQueOrdena = new TableRowSorter<TableModel>(modelo);
        this.jTable1.setRowSorter(elQueOrdena);

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        btnCancelar = new javax.swing.JButton();
        btnModificar = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Consultar Servicios");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nombre Servicio", "Tipo", "Local/Tercerizado", "Precio Local", "Precio Tercerizado"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Double.class, java.lang.Double.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(jTable1);

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/cancelar.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        btnModificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/Modificar.png"))); // NOI18N
        btnModificar.setText("Modificar");
        btnModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnModificarActionPerformed(evt);
            }
        });

        btnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/quitar.png"))); // NOI18N
        btnEliminar.setText("Eliminar");
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 480, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnModificar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnEliminar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnCancelar)
                        .addGap(14, 14, 14))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnModificar)
                    .addComponent(btnEliminar)
                    .addComponent(btnCancelar))
                .addContainerGap(52, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
       this.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void btnModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnModificarActionPerformed
        
        try {
            this.servicio=this.getServicioSeleccionado();
            if(this.servicio!=null){
                ModificacionServicio modServicio=new ModificacionServicio
                    (null, rootPaneCheckingEnabled,servicio);
                modServicio.setVisible(true);
                //this.actualizarTablaCliente();
            }
            
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Hubo un error al seleccionar el servicio para Modificar","Fallo",JOptionPane.ERROR_MESSAGE);
        }
        try {
            this.cargarTablaServicio();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Hubo un error al mostrar la tabla de servicios.","Fallo",JOptionPane.ERROR_MESSAGE);
        }
    
    }//GEN-LAST:event_btnModificarActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
                
        try {
            this.servicio=this.getServicioSeleccionado();
            if(this.servicio!=null){
                int opcion=JOptionPane.showConfirmDialog(null, "Realmente desea Eliminar este servicio", "Confirmar Eliminar", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                if(opcion==JOptionPane.YES_OPTION)
                    this.adm.eliminarServicio(servicio.getCodServicio());
     
            }
        }
        catch (java.lang.IndexOutOfBoundsException e){
             JOptionPane.showMessageDialog(null, "No se selecciono un servicio.", "Aviso", JOptionPane.INFORMATION_MESSAGE);
        } catch (HeadlessException e) {
            
        }catch(SQLException ex){
            JOptionPane.showMessageDialog(null, "Hubo un error, no se pudo eliminar el servicio.", "Error", JOptionPane.ERROR_MESSAGE);
        }
        try {
            this.cargarTablaServicio();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Hubo un error al mostrar la tabla de servicios.","Fallo",JOptionPane.ERROR_MESSAGE);
        }
            
    }//GEN-LAST:event_btnEliminarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(BuscarServicios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(BuscarServicios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(BuscarServicios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(BuscarServicios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                BuscarServicios dialog = new BuscarServicios(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnModificar;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables

    private void cargarTabla() {
        DefaultTableModel modelo=(DefaultTableModel)this.jTable1.getModel();
        for(Servicio servicio: servicios){
            String provisto;
            if(servicio.esTercerizado()) {
                provisto="Tercerizado";
            }
            else
                provisto="Local";
            Object []fila={servicio.getNombre(),servicio.getTipoServicio(),provisto,servicio.getPrecio(),servicio.getPrecioProveedor()};
            modelo.addRow(fila);
        }
    }

    private Servicio getServicioSeleccionado() {
        int posicion=this.jTable1.getSelectedRow();
        String nombre = jTable1.getValueAt(posicion, 0).toString();
        for(Servicio servicio: servicios){
            if(nombre.equals(servicio.getNombre()))
                return servicio;
        }
        return null;
            
    }
    
    
   private void cargarTablaServicio() throws SQLException{
       
       DefaultTableModel modeloTabla= (DefaultTableModel)this.jTable1.getModel();
       int canFilas=modeloTabla.getRowCount();
       int fila=0;
       for(int i=0;i<canFilas;i++)
            modeloTabla.removeRow(fila);
       
       this.servicios=this.adm.getListaservicios();
       Collections.sort(servicios,new Servicio(0));
       cargarTabla();
   }
   
}
